<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of soaUsers
 *
 * @author dxx
 */

namespace app\common\model\activity;

class SalesActivityChannel extends \think\Model {

    protected $table = 'sales_activity_channel';
    protected $connection = ['database' => 'activity'];

    /**
     * 获取一条记录通过条件
     * @param type $condition 条件
     */
    public function getOne($condition=[]){
        return $this->where($condition)->find();
    }
    
    
     /**
     * 获取未投放渠道列表
     * @param type $params
     */
    public function notRunningActivity($params) {

        $list = $where = [];
        if (!empty($params['keywords'])) {
            $where['channel_name'] = ['like',"%{$params['keywords']}%"];
        }
        $where['sales_channel.company_id'] = $params['company_id'];
        $channelIds = $this->setTable('sales_activity_channel')->where(['activity_id' => $params['activity_id']])->column('channel_id');
        
        if (!empty($channelIds)) {
            $where['id'] = ['not in',array_unique($channelIds)];
        }
        
        $salesChannelModel = new SalesChannel();
        $count = $salesChannelModel->where($where)->count();
        
        if ($count) {
            $page = isset($params['page']) ? (int) $params['page'] : 1;
            $pageSize = isset($params['pageSize']) ? (int) $params['pageSize'] : 10;

            $list = $salesChannelModel->where($where)->page($page,$pageSize)->select();
        }else{
            $count = 0;
        }
        return [
            'page'  => (int) $page,
            'count' => (int) $count,
            'list'  => $list
        ];
    }
    
    
    /**
     * 关联活动到渠道
     * @param type $activityId
     * @param type $channelId
     */
    public function activityWithChannel($companyId, $activityId, $channelId) {

        $data = [
            'activity_id' => $activityId,
            'channel_id'  => $channelId,
            'company_id'  => $companyId,
            'add_date'    => time(),
        ];
        return $this->setTable('sales_activity_channel')->insertGetId($data);
    }
    
    
    /**
     * 关闭投放渠道
     * @param type $id
     */
    public function switchStatus($id, $status) {        
        return $this->setTable('sales_activity_channel')->where(['id' => $id])
                ->update(['status' => $status]);
    }
}